import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { queryParkinglotNames } from '../Parking/Spot/service';
import { queryParkingOrders } from './service';
import type { ParkingOrderTableItem } from './types.d';
import { ParkingOrderStatus } from './types.d';
import { PayStatus } from './types.d';
import { PayMode } from './types.d';
import { useRef, useState } from 'react';
import { Badge } from 'antd';
import { useHistory, useModel } from 'umi';
import ExportOrder from './components/ExportOrder';
import { Auths, Role } from '@/utils/types.d';
import OutOrder from './components/OutOrder';

export default () => {
  const { initialState } = useModel('@@initialState');
  const [currOrderNo, setCurrOrderNo] = useState<string>('');
  // const [orderDetailVisible, setOrderDetailVisible] = useState<boolean>(false);
  const currUser = initialState?.currentUser;
  const isAdmin = currUser?.role === Role.ADMIN;
  const auths = currUser?.auth ? new Set(currUser.auth.parkingOrder || []) : new Set();
  const ifExport = auths.has(Auths.EXPORT);
  const ref = useRef<ActionType>();
  const [outVisible, setOutVisible] = useState<boolean>(false);
  const history = useHistory();
  const columns: ProColumns<ParkingOrderTableItem>[] = [
    {
      title: '所属用户',
      align: 'center',
      hideInTable: currUser?.role != Role.ADMIN,
      dataIndex: ['ownerInfo', 'ownerName'],
      hideInSearch: true,
    },
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      align: 'center',
      hideInForm: true,
      renderText: (text, record) => {
        if (record.isImport) return text + '(导)';
        return text;
      },
    },
    {
      title: '停车记录编号',
      dataIndex: 'parkingRecord',
      align: 'center',
    },
    {
      title: '路段名称',
      dataIndex: 'parkingLotId',
      hideInForm: true,
      align: 'center',
      render: (_, record) => record.parkingLotName,
      fieldProps: { showSearch: true },
      debounceTime: 300,
      request: (val) => queryParkinglotNames(val.keyWords),
    },
    {
      title: '泊位编号',
      dataIndex: 'spotId',
      hideInForm: true,
      // hideInTable: true,
      align: 'center',
      order: 2,
    },
    {
      title: '车牌号码',
      dataIndex: 'plateNumber',
      align: 'center',
      hideInForm: true,
      order: 1,
    },

    {
      title: '车辆类型',
      dataIndex: 'vehicleType',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      width: 100,
      valueEnum: {
        0: { text: '普通小型车' },
        1: { text: '普通大型车' },
        2: { text: '新能源小型车' },
        3: { text: '新能源大型车' },
        4: { text: '警车' },
        5: { text: '武警' },
      },
      renderText: (_, record) => {
        if (!record.plateNumber) return '暂无数据';
        return _;
      },
    },
    // {
    //   title: '作废状态',
    //   dataIndex: 'canceled',
    //   align: 'center',
    //   hideInForm: true,
    //   valueEnum: {
    //     true: <Badge color="#666" text="已作废" />,
    //     false: <Badge status="default" text="未作废" />,
    //   },
    // },
    {
      title: '订单状态',
      dataIndex: 'status',
      align: 'center',
      hideInForm: true,
      valueEnum: {
        1: { text: '正常', status: 'Success' },
        2: { text: '未开票', status: 'Error' },
        3: { text: '车牌未录入', status: 'Error' },
        4: { text: '欠费', status: 'Error' },
        99: { text: '未知异常', status: 'Error' },
        1001: { text: '已作废', status: 'Error' },
      },
      render: (_, record) => {
        if (record.canceled) return <Badge color="#666" text="已作废" />;
        switch (record.status) {
          case ParkingOrderStatus.NORMAL:
            return <Badge status="success" text="正常" />;
          case ParkingOrderStatus.ARREAR:
            return <Badge status="error" text="欠费" />;
          case ParkingOrderStatus.NOT_ENTRIED:
            return <Badge status="error" text="车牌未录入" />;
          case ParkingOrderStatus.NOT_PRINT:
            return <Badge status="error" text="未开票" />;
          default:
            return <Badge status="error" text="未知异常" />;
        }
      },
    },
    {
      title: '是否结束',
      dataIndex: 'isEnded',
      align: 'center',
      hideInForm: true,
      valueEnum: {
        true: { text: '结束', status: 'Default' },
        false: { text: '进行中', status: 'Processing' },
      },
      render: (_, record) => {
        if (record.canceled) return '-';
        if (record.isEnded) return <Badge status="default" text="结束" />;
        return <Badge status="processing" text="进行中" />;
      },
    },
    {
      title: '应收金额',
      dataIndex: 'payableAmount',
      hideInSearch: true,
      width: 80,
      align: 'center',
      valueType: 'money',
      renderText: (text) => (text / 100).toFixed(2),
    },
    {
      title: '实收金额',
      dataIndex: 'actualAmount',
      hideInSearch: true,
      align: 'center',
      valueType: 'money',
      renderText: (text) => (text / 100).toFixed(2),
    },
    {
      title: '支付状态',
      dataIndex: 'payStatus',
      align: 'center',
      hideInForm: true,
      valueEnum: {
        0: { text: '免费', status: 'Success' },
        1: { text: '未付', status: 'Error' },
        2: { text: '未结清', status: 'Processing' },
        3: { text: '已结清', status: 'Success' },
        4: { text: '已退款', status: 'Default' },
        5: { text: '待退款', status: 'Error' },
        99: { text: '未结算', status: 'Default' },
      },
      render: (_, record) => {
        if (record.canceled) return '-';
        switch (record.payStatus) {
          case PayStatus.FREE:
            return <Badge status="success" text="免费" />;
          case PayStatus.WAITING:
            return <Badge status="error" text="未付" />;
          case PayStatus.PARI_PAID:
            if (record.payableAmount == record.actualAmount)
              return <Badge status="processing" text="已支付" />;
            return <Badge status="processing" text="未结清" />;
          case PayStatus.FULL_PAID:
            return <Badge status="success" text="已结清" />;
          case PayStatus.REFUNDED:
            return <Badge status="default" text="已退款" />;
          case PayStatus.WAIT_REFUND:
            return <Badge status="error" text="待退款" />;
          default:
            return <Badge status="default" text="未结算" />;
        }
      },
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      hideInForm: true,
      hideInTable: true,
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      hideInForm: true,
      hideInTable: true,
      valueType: 'dateTime',
    },
    {
      title: '驶入时间',
      dataIndex: 'inTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      sorter: true,
    },
    {
      title: '开票时间',
      dataIndex: 'ticketPrintTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '驶出时间',
      dataIndex: 'outTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      sorter: true,
    },
    {
      title: '异常审核',
      dataIndex: 'exceptionStatus',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => record.exceptionStatus || 0,
      valueEnum: {
        0: { text: '无异常' },
        1: { text: '异常待审核' },
      },
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createTime',
    //   align: 'center',
    //   hideInForm: true,
    //   hideInSearch: true,
    //   valueType: 'dateTime',
    //   width: 150,
    // },
    {
      title: '订单来源',
      dataIndex: 'isImport',
      hideInTable: true,
      hideInForm: true,
      valueEnum: {
        true: { text: '外部导入' },
        false: { text: '系统生成' },
      },
    },
    {
      title: '支付方式',
      align: 'center',
      dataIndex: 'payMode',
      hideInSearch: true,
      valueEnum: {
        [PayMode.TENPAY]: { text: '微信支付' },
        [PayMode.ALIPAY]: { text: '支付宝' },
        [PayMode.CASH]: { text: '现金支付' },
        [PayMode.ETC]: { text: 'ETC助缴' },
        [PayMode.UNKNOWN]: { text: '其他' },
      },
    },
    {
      title: '车牌已录入',
      dataIndex: 'isEntried',
      align: 'center',
      hideInForm: true,
      hideInTable: true,
      valueEnum: {
        true: { text: '是' },
        false: { text: '否' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (_, record) => [
        // <FlowPath currRecord={record} />,
        <a
          key={record.orderNo}
          onClick={() => {
            // setCurrOrderNo(record.orderNo);
            // setOrderDetailVisible(true);
            history.push({
              pathname: '/parking-orders/detail',
              state: record.orderNo,
            });
          }}
        >
          详情
        </a>,
        isAdmin && !record.carOut && (
          <a
            key={`out_${record.orderNo}`}
            onClick={() => {
              setCurrOrderNo(record.orderNo);
              setOutVisible(true);
            }}
          >
            驶出
          </a>
        ),
      ],
    },
  ];

  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '订单管理',
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            { path: '/order', breadcrumbName: '订单管理' },
            { path: '/order/parking-list', breadcrumbName: '订单列表' },
          ],
        },
      }}
    >
      <ProTable<ParkingOrderTableItem>
        columns={columns}
        rowKey="orderNo"
        scroll={{ x: true }}
        search={{ labelWidth: 'auto' }}
        style={{ whiteSpace: 'nowrap' }}
        columnEmptyText="暂无数据"
        actionRef={ref}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryParkingOrders(param, sort);
          return res;
        }}
        toolBarRender={() => [ifExport && <ExportOrder />]}
      />
      {/* <ModalDetail
        orderNo={currOrderNo}
        visible={orderDetailVisible}
        close={() => {
          setOrderDetailVisible(false);
          setCurrOrderNo('');
          ref.current?.reload();
        }}
      /> */}
      {isAdmin && outVisible && (
        <OutOrder
          orderNo={currOrderNo}
          visible={outVisible && isAdmin}
          close={() => {
            setCurrOrderNo('');
            setOutVisible(false);
            ref.current?.reload();
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};
